﻿using System;
using GeoAPI.Geometries;

namespace YJKGridTopologyCal.Algorithm
{
	public class InteriorPointLine
	{
		public InteriorPointLine(IGeometry g)
		{
			this._centroid = g.Centroid.Coordinate;
			this.AddInterior(g);
			if (this._interiorPoint == null)
			{
				this.AddEndpoints(g);
			}
		}

		public Coordinate InteriorPoint
		{
			get
			{
				return this._interiorPoint;
			}
		}

		private void AddInterior(IGeometry geom)
		{
			if (geom is ILineString)
			{
				this.AddInterior(geom.Coordinates);
				return;
			}
			if (geom is IGeometryCollection)
			{
				foreach (IGeometry geom2 in ((IGeometryCollection)geom).Geometries)
				{
					this.AddInterior(geom2);
				}
			}
		}

		private void AddInterior(Coordinate[] pts)
		{
			for (int i = 1; i < pts.Length - 1; i++)
			{
				this.Add(pts[i]);
			}
		}

		private void AddEndpoints(IGeometry geom)
		{
			if (geom is ILineString)
			{
				this.AddEndpoints(geom.Coordinates);
				return;
			}
			if (geom is IGeometryCollection)
			{
				foreach (IGeometry geom2 in ((IGeometryCollection)geom).Geometries)
				{
					this.AddEndpoints(geom2);
				}
			}
		}

		private void AddEndpoints(Coordinate[] pts)
		{
			this.Add(pts[0]);
			this.Add(pts[pts.Length - 1]);
		}

		private void Add(Coordinate point)
		{
			double num = point.Distance(this._centroid);
			if (num < this._minDistance)
			{
				this._interiorPoint = new Coordinate(point);
				this._minDistance = num;
			}
		}

		private readonly Coordinate _centroid;

		private double _minDistance = double.MaxValue;

		private Coordinate _interiorPoint;
	}
}
